package top.oylan.manager.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.oylan.manager.entity.*;
import top.oylan.manager.entity.example.ProductExample;
import top.oylan.manager.entity.example.WatchedExample;
import top.oylan.manager.entity.extend.BookCondition;
import top.oylan.manager.entity.extend.WatchedExtend;
import top.oylan.manager.entity.mp.MpRecommended;
import top.oylan.manager.entity.mp.MpVideo;
import top.oylan.manager.mapper.CategoryMapper;
import top.oylan.manager.mapper.ProductMapper;
import top.oylan.manager.mapper.WatchedMapper;
import top.oylan.manager.service.ProductService;
import top.oylan.manager.tools.Pager;
import top.oylan.manager.tools.SystemConstants;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service("product")
public class ProductServiceImpl implements ProductService {

    @Resource
    ProductMapper productMapper;

    @Resource
    CategoryMapper categoryMapper;

    /**
     * type  1 课程 ， 2 连续剧 ，3 电影 ， 4 纪录片 ，5 动画 ，
     * 6 =（2，4）, 7 = (3,4) ， 8 = （2，5），9 = （3，5），10 = （4，5），11=（2，4，5），12=（3，4，5）
     * @param pager
     * @param type
     */
    public void getProductCount(Pager pager,int type){

        Product condition = (Product) pager.getCondition();
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        
        if(condition.getStatus() != null){
            criteria.andStatusEqualTo(condition.getStatus());
        }
        switch (type){
            case SystemConstants.FILM_NOTICE:
                criteria.andTypeIn(Arrays.asList((byte)SystemConstants.FILM,(byte)SystemConstants.NOTICE));
                break;
            case SystemConstants.MOVIE_NOTICE:
                criteria.andTypeBetween((byte)SystemConstants.MOVIE,(byte)SystemConstants.NOTICE);
                break;
            case SystemConstants.FILM_CARTON:
                criteria.andTypeIn(Arrays.asList((byte)SystemConstants.FILM,(byte)SystemConstants.CARTON));
                break;
            case SystemConstants.MOVIE_CARTON:
                criteria.andTypeIn(Arrays.asList((byte)SystemConstants.MOVIE,(byte)SystemConstants.CARTON));
                break;
            case SystemConstants.NOTICE_CARTON:
                criteria.andTypeBetween((byte)SystemConstants.NOTICE,(byte)SystemConstants.CARTON);
                break;
            case SystemConstants.FILM_NOTICE_CARTON:
                criteria.andTypeIn(Arrays.asList((byte)SystemConstants.FILM,(byte)SystemConstants.NOTICE,(byte)SystemConstants.CARTON));
                break;
            case SystemConstants.MOVIE_NOTICE_CARTON:
                criteria.andTypeBetween((byte)SystemConstants.MOVIE,(byte)SystemConstants.CARTON);
                break;
            default:
                criteria.andTypeEqualTo(condition.getType());
                break;
        }
        if(condition.getScope() != null){
           if(condition.getScope() == 4){
               criteria.andScopeBetween((byte)2,(byte)3);
           } else{
               criteria.andScopeEqualTo(condition.getScope());
           }
        }
        if(condition.getCateId() != null){
            criteria.andCateIdEqualTo(condition.getCateId());
        }else if(condition.getCateIdStr()!= null){
            criteria.andCateIdIn(condition.getCateIdStr());
        } else{
            List<Category> categories = categoryMapper.selectCategoryByType(type);
            List<Short> cateIds = new ArrayList<>();
            for(Category category:categories){
                cateIds.add(category.getId().shortValue());
            }
            if(cateIds.size() > 0){
                criteria.andCateIdIn(cateIds);
                condition.setCateIdStr(cateIds);
            }
            pager.setCondition(condition);
        }
        pager.setTotalRow( (int)productMapper.countByExample(example));
    }

    @Override
    public List<Course> selectCourseByPager(Pager pager) {

        getProductCount(pager,SystemConstants.COURSE);
        return  productMapper.selectCourseByPager(pager);
    }

    @Override
    public List<Video> selectVideoByPager(Pager pager) {
        Product cond = (Product)pager.getCondition();
        int type = cond.getType()!=null?cond.getType():SystemConstants.FILM_NOTICE_CARTON;
        cond.setType((byte)type);
        pager.setCondition(cond);
        getProductCount(pager,type);
        return productMapper.selectVideoByPager(pager);
    }

    @Override
    public List<Video> selectMovieByPager(Pager pager) {

        Product cond = (Product)pager.getCondition();
        int type = cond.getType()!=null?cond.getType():SystemConstants.MOVIE_NOTICE_CARTON;
        cond.setType((byte)type);
        pager.setCondition(cond);
        getProductCount(pager,type);
        return productMapper.selectVideoByPager(pager);
    }

    @Override
    public List<Recommended> selectRecommendByType(int type,Pager pager) {
        int offset = (pager.getCurrentPage() - 1) * pager.getEveyPageRow();
        return productMapper.selectRecommendByType(type,offset,pager.getCurrentPage());
    }

    @Override
    public List<Recommended> selectRecommendByType(int type) {
        return productMapper.selectRecommendByType(type,null,null);
    }

    @Override
    public int countByType(int type) {
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte)type);
        return (int)productMapper.countByExample(example);
    }

    @Override
    public ArrayList<Product> selectByType(int type) {
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte)type);
        return productMapper.selectByExample(example);
    }

    @Override
    public Course selectProductById(Integer id) {
        return productMapper.findCourseByPrimaryKey(id);
    }

    @Override
    public int updateProduct(Product product) {
        return productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public int addProduct(Product product) {
        return productMapper.insertSelective(product);
    }

    @Override
    public int delete(Integer id) {
        return productMapper.deleteByPrimaryKey(id);
    }

    // for-api
    @Override
    public ArrayList<Video> selectProductByPager(Pager pager) {
        Product condition = (Product) pager.getCondition();
        getProductCount(pager,(short)condition.getType());
        return productMapper.selectProductByPager(pager);
    }

    @Override
    public int setRecommend(Byte type, List<Integer> ids) {
         Integer del = productMapper.deleteRecommendByType(type);
         Integer set = productMapper.setRecommend(type, ids);
         return (del > 0 && set >0)?1:0;
    }

    @Override
    public int deleteRecommend(int id) {
        return productMapper.deleteRecommendById(id);
    }

    // for-mp
    @Override
    public List<MpRecommended> selectRecommendedForMp(){
        return productMapper.selectRecommendForMp();
    }

    @Override
    public MpVideo findVideoById(Integer id,Integer userId) {
        return productMapper.findVideoById(id,userId);
    }

    @Override
    public Product findBaseInfoById(Integer id) {
        return productMapper.findBaseInfoById(id);
    }

    @Override
    public List<WatchedExtend> selectMyCourse(Pager pager) {
        return productMapper.selectMyCourseByPager(pager);
    }

    @Override
    public List<WatchedExtend> selectMyWatched(Integer userId) {
        return productMapper.selectMyWatched(userId);
    }

    @Resource
    WatchedMapper watchedMapper;

    @Override
    public Watched findUserWatched(Watched watched) {
        return watchedMapper.findUserWatched(watched);
    }

    @Override
    public int saveWatched(Watched watched) {
        int res = 0;
        if(watched.getId()!=null && watched.getId() > 0){
            // 更新
            WatchedExample watchedExample = new WatchedExample();
            WatchedExample.Criteria criteria = watchedExample.createCriteria();
            criteria.andIdEqualTo(watched.getId());
            res = watchedMapper.updateByExampleSelective(watched,watchedExample);
        }else{
            // 新增
            res = watchedMapper.insertSelective(watched);
        }
        return res;
    }

    @Override
    public List<Book> selectBooksByPager(Pager pager) {
        Product condition = new Product();
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte)6);
        if(!StringUtils.isEmpty(condition.getTitle())){
            criteria.andTitleLike(condition.getTitle());
        }
        long count = productMapper.countByExample(example);
        pager.setTotalRow((int)count);
        List<Book> list = productMapper.selectBooksByPager(pager);
        return list;
    }

    @Override
    public int watch(Integer id) {
        return productMapper.watch(id);
    }

    @Override
    public List<Book> selectMyBooksByPager(Pager pager) {
        int count = productMapper.countMyBooks((BookCondition) pager.getCondition());
        pager.setTotalRow(count);
        return productMapper.selectMyBooksByPager(pager);
    }
}
